loginApp.service('loginService', ['$rootScope', '$window', '$location', '$http',
    function($rootScope, $window, $location, $http) {
        var userName;

        destroy = function() {
            delete $window.sessionStorage.token;
            delete $window.sessionStorage.profile;
            userName = "";
            $rootScope.$emit('logged out');
            $location.path('/login');
        }

        this.getUserName = function() {
            return userName;
        }
        this.setUserName = function(userName) {
            this.userName = userName;
        }
        this.login = function(credentials) {
            $http
                .put('/login/users', credentials)
                .success(function(data, status, headers, config) {
                    var encodedProfile = data.token.split('.')[1];
                    var profile = JSON.parse(url_base64_decode(encodedProfile));
                    userName = profile.username;
                    $window.sessionStorage.token = data.token;
                    $rootScope.$emit('logged in');
                    $location.path($rootScope.locationBeforeLogin);
                })
                .error(function(data, status, headers, config) {
                    // Erase the token if the user fails to log in
                    destroy();
                })
        }
        this.logout = function() {
            destroy();
        }
        this.isAuthenticated = function() {
            return !!$window.sessionStorage.token;
        }
    }
])